package com.quectel.cms.controller.securitypatrol;


import com.quectel.business.common.securitypatrolsubject.SecurityPatrolBussiness;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolSubjectDto;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolSubjectService;
import com.quectel.util.common.POIUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:09
 */
@RestController
@RequestMapping("securityPatrolSubject")
@Tag(name = "SecurityPatrolSubjectController", description = "巡检项目相关api")
public class SecurityPatrolSubjectController extends BaseController {

    @DubboReference
    private SecurityPatrolSubjectService securityPatrolSubjectService;
    @Autowired
    private SecurityPatrolBussiness securityPatrolBussiness;

    @PostMapping("importExcel")
    @RequirePermissions(values = "securityPatrolSubject:importExcel")
    @Operation(summary = "excel导入巡检项目")
    @Log(express = "导入巡检项目")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request, String category
    ) {
        Long tenantId = SessionHolder.getSysUser().getTenantId();
        Date now = new Date();
        List<SecurityPatrolSubjectDto> list = new ArrayList<>();
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    //校验数据合法性
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);
                    for (Map<Integer, String> map : analysis) {
                        try {
                            if (map.get(0) == null || map.get(0).trim().equals("")
                                    || map.get(1) == null || map.get(1).trim().equals("")) {
                                continue;
                            }
                            SecurityPatrolSubjectDto dto = new SecurityPatrolSubjectDto();
                            dto.setCategory(Byte.valueOf(category));
                            dto.setGroupTypeName(map.get(0));
                            dto.setGroupType(securityPatrolBussiness.getChildTypeValue(dto));
                            dto.setSubject(map.get(1));
                            dto.setProposal(map.get(2));
                            dto.setCreateTime(now);
                            dto.setTenantId(tenantId);
                            fillSaveCommonData(dto);
                            list.add(dto);
                        } catch (Exception e) {
                            continue;
                        }
                    }
                } catch (Exception e) {
                    logger.error("解析巡检项目信息出错");
                }
            }
        }
        int successCount = 0;
        for (SecurityPatrolSubjectDto carDto : list) {
            try {
                successCount++;
                securityPatrolSubjectService.save(carDto);
            } catch (Exception e) {
                logger.error("导入失败", e);
                continue;
            }
        }
        return Response.error("导入成功,导入成功数量为:" + successCount);
    }

    /**
     * 导出巡检项目信息为excel
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "securityPatrolSubject:exportExcel")
    @Log(express = "导出巡检项目信息")
    @Operation(summary = "导出巡检项目信息为excel")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<SecurityPatrolSubjectDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<SecurityPatrolSubjectDto> list = securityPatrolSubjectService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"巡检大类", "巡检分组", "巡检项目名称", "巡检指导"};
        List<String[]> dataList = new ArrayList<>();
        for (SecurityPatrolSubjectDto data : result) {
            String[] item = new String[headers.length];
            item[0] = securityPatrolBussiness.getCategoryAndType(data)[0];
            item[1] = securityPatrolBussiness.getCategoryAndType(data)[1];
            item[2] = data.getSubject();
            item[3] = data.getProposal();
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "巡检项目", headers, dataList, "巡检项目");

    }

    /**
     * 巡检项目分页查询列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "securityPatrolSubject:list")
    @Operation(summary = "巡检项目分页查询列表")
    public Response<Page<SecurityPatrolSubjectDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = securityPatrolSubjectService.queryTotal(request.getParams());

        List<SecurityPatrolSubjectDto> list = null;
        if (total > 0) {
            list = securityPatrolSubjectService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<SecurityPatrolSubjectDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SecurityPatrolSubjectDto>>ok().wrap(page);
    }


    /**
     * 查询巡检项目单条记录，编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "securityPatrolSubject:edit")
    @Operation(summary = "查询巡检项目单条记录，编辑反显查询")
    public Response<SecurityPatrolSubjectDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolSubjectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolSubjectDto securityPatrolSubjectDto = securityPatrolSubjectService.selectById(id);

        return Response.<SecurityPatrolSubjectDto>ok().wrap((securityPatrolSubjectDto));
    }

    /**
     * 查询巡检项目单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "securityPatrolSubject:info")
    @Operation(summary = "查询巡检项目单条记录")
    public Response<SecurityPatrolSubjectDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolSubjectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolSubjectDto securityPatrolSubjectDto = securityPatrolSubjectService.selectById(id);

        return Response.<SecurityPatrolSubjectDto>ok().wrap((securityPatrolSubjectDto));
    }

    /**
     * 保存巡检项目单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "securityPatrolSubject:edit")
    @Operation(summary = "保存巡检项目单条记录")
    public Response<Object> save(@RequestBody @Validated SecurityPatrolSubjectDto securityPatrolSubjectDto) {

        //填充基础数据
        fillSaveCommonData(securityPatrolSubjectDto);

        securityPatrolSubjectService.save(securityPatrolSubjectDto);

        return Response.ok();
    }

    /**
     * 修改巡检项目单条记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "securityPatrolSubject:edit")
    @Operation(summary = "修改巡检项目单条记录")
    public Response<Object> update(@RequestBody @Validated SecurityPatrolSubjectDto securityPatrolSubjectDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(securityPatrolSubjectDto.getId()));
        if (securityPatrolSubjectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(securityPatrolSubjectDto);

        securityPatrolSubjectService.updateById(securityPatrolSubjectDto);

        return Response.ok();
    }

    /**
     * 批量删除巡检项目单条记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "securityPatrolSubject:delete")
    @Operation(summary = "批量删除巡检项目单条记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (securityPatrolSubjectService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        securityPatrolSubjectService.deleteBatch(ids);

        return Response.ok();
    }
}
